import sys
import os

path = os.path.dirname(os.path.abspath(sys.argv[0]).replace('\\', '/')) + '/'
for i in range(1, len(path.split('/')) - 2):
    sys.path.append(path + '../' * i)

from util.lib.Util import Util
from util.lib.STD import STD


class Linux_task:
    def __init__(self):
        self.file = None
        self.cmd = None
        self.check_cmd = None
        self.init()
        self.run()

    def init(self):
        try:
            self.file = sys.argv[1]
        except:
            STD.die('no path')
        try:
            self.cmd = sys.argv[2]
        except:
            self.cmd = 'check'
        self.check_cmd = 'ps -ef | grep ' + self.file + ' | grep -v grep | grep -v Linux_task | grep -v source'

    def run(self):
        getattr(self, self.cmd)()

    def restart(self):
        self.stop()
        self.start()

    def stop(self):
        cmd = self.check_cmd + '| awk \'{print $2}\' | xargs kill -9'
        res = Util.cmd_mix(cmd)
        if res['code'] == 0:
            print('stop ok')
        else:
            STD.die('stop fail')

    def get_start_cmd(self, exe):
        cmd = 'nohup ' + exe + ' ' + self.file + " &> " + self.file + "_.log &"
        return cmd

    def start(self):
        ext = self.file.split('.')[-1]
        cmdArr = []
        res = {'code': 1}
        if ext == 'php':
            cmdArr.append(self.get_start_cmd('php7'))
            cmdArr.append(self.get_start_cmd('php'))
        elif ext == 'py':
            cmdArr.append(self.get_start_cmd('python3'))
            cmdArr.append(self.get_start_cmd('python'))
        cmd = ''
        while len(cmdArr):
            try:
                cmd = cmdArr.pop()
                res = Util.cmd_tmp(cmd)
                break
            except:
                continue
        if res['code'] == 0:
            print('start ok:' + cmd)
        else:
            STD.die('start fail')

    def check(self):
        res = Util.cmd_mix(self.check_cmd)
        if len(res['content']) < 2:
            self.restart()
        else:
            print(res['content'])


if __name__ == '__main__':
    Linux_task()
